﻿using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QYmall.Core.API.Controllers.Base
{
    /// <summary>
    /// 商户菜单接口
    /// </summary>
    [Route("admin/merchant/menu")]
    [ApiController]
    public class MerchantMenuController : ControllerBase
    {
        private readonly IMerchantMenuService _merchantMenuService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;
        
        public MerchantMenuController(IMerchantMenuService merchantMenuService, IUserService userService, IMapper mapper)
        {
            _merchantMenuService = merchantMenuService;
            _userService = userService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 获取导航树目录列表
        /// 示例：/admin/merchant/menu
        /// </summary>
        [HttpGet]
        [Authorize]
        [AuthorizeFilter("MerchantMenu", ActionType.View)]
        public async Task<IActionResult> GetList([FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<MerchantMenuDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //如果有查询关健字
            var parentId = 0; //父节点ID
            if (param.Keyword.IsNotNullOrWhiteSpace())
            {
                var model = await _merchantMenuService.QueryAsync<MerchantMenu>(x => x.Title != null && x.Title.Contains(param.Keyword));
                if (model == null)
                {
                    return BadRequest(ResponseMessage.Error("暂无查询记录"));
                }
                parentId = model.Id;
            }
            //获取数据库列表
            var resultFrom = await _merchantMenuService.QueryListAsync(parentId);
            //使用AutoMapper转换成ViewModel
            //根据字段进行塑形
            var resultDto = resultFrom.AsEnumerable().ShapeData(param.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 根据ID获取导航
        /// 示例：/admin/merchant/menu/1
        /// </summary>
        [HttpGet("{navId}")]
        [Authorize]
        [AuthorizeFilter("MerchantMenu", ActionType.View)]
        public async Task<IActionResult> GetById([FromRoute] int navId, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<MerchantMenuDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var model = await _merchantMenuService.QueryAsync<MerchantMenu>(x => x.Id == navId, WriteRoRead.Write);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{navId}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel
            //根据字段进行塑形
            var result = _mapper.Map<MerchantMenuDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/admin/merchant/menu
        /// </summary>
        [HttpPost]
        [Authorize]
        [AuthorizeFilter("MerchantMenu", ActionType.Add)]
        public async Task<IActionResult> Add([FromBody] MerchantMenuEditDto modelDto)
        {
            if (modelDto.Name == null)
            {
                return BadRequest(new ResponseMessage(ErrorCode.RepeatField, $"请填写菜单的英文名称"));
            }
            //检查站点名称是否重复
            if (await _merchantMenuService.ExistsAsync<MerchantMenu>(x => x.Name != null && x.Name.ToLower().Equals(modelDto.Name.ToLower())))
            {
                return BadRequest(new ResponseMessage(ErrorCode.RepeatField, $"菜单{modelDto.Name}已存在"));
            }
            //映射成实体
            var model = _mapper.Map<MerchantMenu>(modelDto);
            //写入数据库
            var sourceModel = await _merchantMenuService.AddAsync(model);
            //映射成DTO再返回，否则出错
            var result = _mapper.Map<MerchantMenuDto>(sourceModel);
            return Ok(result);
        }

        /// <summary>
        /// 修改一条记录
        /// 示例：/admin/merchant/menu/1
        /// </summary>
        [HttpPut("{navId}")]
        [Authorize]
        [AuthorizeFilter("MerchantMenu", ActionType.Edit)]
        public async Task<IActionResult> Update([FromRoute] int navId, [FromBody] MerchantMenuEditDto modelDto)
        {
            if (modelDto.Name == null)
            {
                return BadRequest(new ResponseMessage(ErrorCode.RepeatField, $"请填写菜单的英文名称"));
            }
            //查找站点信息
            var model = await _merchantMenuService.QueryAsync<MerchantMenu>(x => x.Id == navId);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据{navId}不存在或已删除"));
            }
            //检查站点名称是否重复
            if (model.Name?.ToLower() != modelDto.Name.ToLower()
                && await _merchantMenuService.ExistsAsync<MerchantMenu>(x => x.Name != null && x.Name.ToLower() == modelDto.Name.ToLower()))
            {
                return BadRequest(new ResponseMessage(ErrorCode.RepeatField, $"菜单{modelDto.Name}已存在"));
            }
            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelDto, model);
            var result = await _merchantMenuService.SaveAsync();
            return NoContent();
        }

        /// <summary>
        /// 局部更新一条记录
        /// 示例：/admin/merchant/menu/1
        /// Body：[{"op":"replace","path":"/title","value":"new title"}]
        /// </summary>
        [HttpPatch("{navId}")]
        [Authorize]
        [AuthorizeFilter("MerchantMenu", ActionType.Edit)]
        public async Task<IActionResult> Update([FromRoute] int navId, [FromBody] JsonPatchDocument<MerchantMenuEditDto> patchDocument)
        {
            var model = await _merchantMenuService.QueryAsync<MerchantMenu>(x => x.Id == navId);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据{navId}不存在或已删除"));
            }

            var modelToPatch = _mapper.Map<MerchantMenuEditDto>(model);
            patchDocument.ApplyTo(modelToPatch, ModelState);
            //验证数据是否合法
            if (!TryValidateModel(modelToPatch))
            {
                return ValidationProblem(ModelState);
            }
            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelToPatch, model);
            await _merchantMenuService.SaveAsync();

            return NoContent();
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/admin/merchant/menu/1
        /// </summary>
        [HttpDelete("{navId}")]
        [Authorize]
        [AuthorizeFilter("MerchantMenu", ActionType.Delete)]
        public async Task<IActionResult> Delete([FromRoute] int navId)
        {
            if (!await _merchantMenuService.ExistsAsync<MerchantMenu>(x => x.Id == navId))
            {
                return BadRequest(ResponseMessage.Error($"数据{navId}不存在或已删除"));
            }
            await _merchantMenuService.DeleteAsync(x => x.Id == navId);
            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/admin/merchant/menu?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        [AuthorizeFilter("MerchantMenu", ActionType.Delete)]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var areaIds = Ids.ToIEnumerable<int>();
            if (areaIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _merchantMenuService.DeleteAsync(x => areaIds.Contains(x.Id));
            return NoContent();
        }
        #endregion

        #region 当前账户调用接口========================
        /// <summary>
        /// 获取管理员导航树目录列表
        /// 示例：/account/merchant/menu
        /// </summary>
        [HttpGet("/account/merchant/menu")]
        [Authorize]
        public async Task<IActionResult> GetNavList([FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<MerchantMenuDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取数据库列表
            var resultFrom = await _merchantMenuService.QueryListAsync();
            //根据字段进行塑形，使用AutoMapper转换成ViewModel
            var resultDto = resultFrom.AsEnumerable().ShapeData(param.Fields);
            //返回成功200
            return Ok(resultDto);
        }
        #endregion
    }
}
